package vulnapp.controller;

import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import vulnapp.dto.LocationDto;
import vulnapp.entity.Location;
import vulnapp.service.LocationService;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;


@Controller
public class LocationController {

    @Autowired
    DataSource dataSource;

    private final LocationService locationService;

    public LocationController(LocationService locationService) {
        this.locationService = locationService;
    }

    @GetMapping("/search")
    public String findUser(Model model, String code) {

        if(code!=null) {
            List<LocationDto> locations= locationService.unsafeFindLocation(code, dataSource);
            model.addAttribute("locations", locations);
        }else {
            List<LocationDto> locations = new ArrayList<LocationDto>();
            model.addAttribute("locations", locations);
        }
        return "search";
    }

    @GetMapping("/data")
    public String showForm(Model model){
        // create model object to store form data
        LocationDto locationDto = new LocationDto();
        model.addAttribute("location", locationDto);
        return "data";
    }
    @PostMapping("/data/add")
    public String addData(@Valid @ModelAttribute("location") LocationDto locationDto,
                               BindingResult result,
                               Model model){

        Location existingLocation = locationService.findLocationByCoordinates(locationDto.getCoordinates());

        if(existingLocation != null){
            result.rejectValue("coordinates", "conflict",
                    "Данная локация уже есть в базе!");
        }

        if(result.hasErrors()){
            model.addAttribute("location", locationDto);
            return "data";
        }

        locationService.saveLocation(locationDto);
        return "redirect:/data?success";
    }
}